package com.ybl.store.backend.service.UserService;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ybl.store.backend.dao.entity.AdminDO;
import com.ybl.store.backend.dao.entity.ClerkDO;
import com.ybl.store.backend.dao.entity.ManagerDO;
import com.ybl.store.backend.dao.mapper.AdminMapper;
import com.ybl.store.backend.dao.mapper.ClerkMapper;
import com.ybl.store.backend.dao.mapper.ManagerMapper;
import com.ybl.store.common.constant.DelFlag;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户服务
 */
@Component
@RequiredArgsConstructor
public class UserService {

    private final AdminMapper adminMapper;

    private final ManagerMapper managerMapper;

    private final ClerkMapper clerkMapper;

    /**
     * 生成随机用户名
     *
     * @return 用户名
     */
    public String createRandomUsername() {
        String username;

        do {
            username = RandomUtil.randomString(6);
        } while(isUsernameExist(username));

        return username;
    }

    /**
     * 生成随机密码
     *
     * @return 密码
     */
    public String createRandomPassword() {
        return RandomUtil.randomString(6);
    }

    /**
     * 判断用户名是否存在
     *
     * @param username 用户名
     * @return 存在 true 不存在 false
     */
    public boolean isUsernameExist(String username) {
        LambdaQueryWrapper<AdminDO> adminDOLambdaQueryWrapper = Wrappers.lambdaQuery(AdminDO.class)
                .eq(AdminDO::getUsername, username)
                .eq(AdminDO::getDelFlag, DelFlag.present);

        if (adminMapper.selectOne(adminDOLambdaQueryWrapper) != null) {
            return true;
        }

        LambdaQueryWrapper<ManagerDO> managerDOLambdaQueryWrapper = Wrappers.lambdaQuery(ManagerDO.class)
                .eq(ManagerDO::getUsername, username)
                .eq(ManagerDO::getDelFlag, DelFlag.present);

        if (managerMapper.selectOne(managerDOLambdaQueryWrapper) != null) {
            return true;
        }

        LambdaQueryWrapper<ClerkDO> clerkDOLambdaQueryWrapper = Wrappers.lambdaQuery(ClerkDO.class)
                .eq(ClerkDO::getUsername, username)
                .eq(ClerkDO::getDelFlag, DelFlag.present);

        return clerkMapper.selectOne(clerkDOLambdaQueryWrapper) != null;
    }
}
